import cutils from '../../js/common/core-utils.js';
import '../../js/common/table-col-utils.js';

$(function() {
	initTable();

	$(document).keydown(function() {
		if (event.keyCode == 13) {
			doSearch();
		}
	});

	cutils.doAuthSign();
});

self.initTable = function() {
	$('#data-table').treegrid({
		url: "/" + cutils.webApp + "/function/list?_time=" + cutils.now(),
		method: 'get',
		idField: "functionId",
		treeField: "name",
		animate: true,
		fit: true,
		fitColumns: false,
		pagination: false,// 分页控件
		rownumbers: false,// 行号
		loadMsg: false,
		resizeHandle: 'right',
		singleSelect: false,
		checkOnSelect: false,
		selectOnCheck: false,
		nowrap: false,
		emptyMsg: '无数据',
		onLoadSuccess: function(data) {
			layui.form.render();
			$('#data-table').treegrid('unselectAll');
			$('#data-table').treegrid('uncheckAll');

			cutils.doAuthSign();

			var roots = $('#data-table').treegrid("getRoots");
			doCollapse(null, roots);
		},
		onLoadError: function() {
			$(".datagrid-body").html("<div style='width: 100%; height: 50px; line-height: 50px; text-align: center;font-size: 14px;'>数据加载出错</div>");
			$(".datagrid-empty").hide();
		},
		loadFilter: function(data, parentId) {
			if (cutils.notEquals(data.status, 200)) {
				layer.msg(data.message, { icon: 3 });
				return;
			}

			return doFunctionToTree(data.data.dataList);
		},
		columns: [[{
			field: 'name',
			title: '功能名称',
			width: 210
		}, {
			field: 'type',
			title: '功能类型',
			align: 'center',
			width: 80,
			formatter: function(value, row, index) {
				if (value == 0) {
					return "菜单";
				}
				if (value == 1) {
					return "权限";
				}
				return "";
			}
		}, {
			field: 'url',
			title: '链接',
			width: 400,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'code',
			title: '功能标识',
			width: 150,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'desc',
			title: '备注信息',
			width: 200,
			hidden: true
		}, {
			field: 'updatetime',
			title: '更新时间',
			width: 150,
			align: 'center',
			hidden: true,
			formatter: function(value, row, index) {
				return value.length > 16 ? value.substring(0, 16) : value;
			}
		}, {
			field: 'order',
			title: '排序号',
			align: 'center',
			width: 60
		}, {
			field: 'status',
			title: '是否禁用',
			align: 'center',
			width: 85,
			formatter: function(value, row, index) {
				return '<span id="func-status-span-' + row.functionId + '" class="layui-form"><input tipId="#func-status-span-' + row.functionId + '" type="checkbox" name="function-status" functionId="' + row.functionId + '" title="禁用" lay-filter="function-status" ' + (row.status == 1 ? 'checked' : '') + '></span>';
			}
		}, {
			field: 'opts',
			title: '操作',
			width: 120,
			align: 'center',
			formatter: function(value, row, index) {
				let html = '<div title="编辑功能" data-authcode="uums.func.edit" class="hi-small-btn hi-small-normal-btn hi-transition hi-auth-sign" onclick="doEditFunction(' + row.functionId + ');">';
				html += '<i class="fa fa-pencil-square-o" aria-hidden="true"></i>';
				//html +='<span>编辑</span>';
				html += '</div>';

				html += '<div title="新增下级功能" data-authcode="uums.func.add" class="hi-small-btn hi-small-normal-btn hi-transition hi-auth-sign" onclick="doAddFunction(' + row.functionId + ');">';
				html += '<i class="fa fa-plus" aria-hidden="true"></i>';
				//html +='<span>新增</span>';
				html += '</div>';

				html += '<div title="删除功能" data-authcode="uums.func.del" class="hi-small-btn hi-small-txt-red-btn hi-transition hi-auth-sign" onclick="doDelFunction(' + row.functionId + ');">';
				html += '<i class="fa fa-trash-o" aria-hidden="true"></i>';
				// html +='<span>删除</span>';
				html += '</div>';
				return html;
			}
		}]]
	});

	layui.form.on('checkbox(function-status)', function(obj) {
		if (cutils.hasNotAuthCode("uums.func.edit")) {
			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
			layer.tips('没有操作权限', $(obj.elem).attr("tipId"), {
				tips: 1,
				time: 1000
			});
			return false;
		}

		doEidtFunctionStatus(obj);
	});
}

self.doFunctionToTree = function(list) {
	$.each(list, function(i, item) {
		item.hasParent = false;
	});

	$.each(list, function(i, item) {
		item.children = [];
		$.each(list, function(i, subItem) {
			if (item.functionId == subItem.functionPId) {
				subItem.hasParent = true;
				item.children.push(subItem);
			}
		});
	});

	var treeList = [];
	$.each(list, function(i, item) {
		item.iconCls = item.icon;
		if (item.icon == null || item.icon == "") {
			item.iconCls = "fa-paper-plane-o";
		}
		item.iconCls = "fa " + item.iconCls;

		if (item.type == 1) {//权限类型图标
			item.iconCls = "fa-dot-circle-o";
		}

		if (!item.hasParent) {
			treeList.push(item);
		}
	});
	return treeList;
}

self.doSearch = function() {
	var unlock = $("#q-status-unlock").is(":checked");
	var lock = $("#q-status-lock").is(":checked");

	var queryParams = {};
	queryParams["name"] = $("#q-function-name").val();
	queryParams["status"] = unlock && lock ? "" : !unlock && !lock ? "" : unlock ? 0 : 1;
	$('#data-table').treegrid('load', queryParams);
}

self.doEidtFunctionStatus = function(obj) {
	var params = {
		"functionId": $(obj.elem).attr("functionId"),
		"status": obj.elem.checked ? 1 : 0,
	};

	$.ajax({
		type: "put",
		url: "/" + cutils.webApp + "/function/status?_time=" + cutils.now(),
		data: params,
		dataType: 'json',
		success: function(result) {
			if (cutils.equals(result.status, 200)) {
				layer.msg(result.message, { icon: 1, time: 1000 });
				return;
			}

			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
			layer.msg(result.message, { icon: 7 });
		},
		nerror: function(e) {
			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
		}
	});
}

self.doDelFunction = function(functionId) {
	layer.confirm('确定删除吗?',
		{
			icon: 3,
			title: '温馨提示',
			btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
			yes: function(index) {
				layer.close(index);
				$.ajax({
					type: "delete",
					url: "/" + cutils.webApp + "/function/" + functionId + "?_time=" + cutils.now(),
					dataType: 'json',
					success: function(result) {
						if (cutils.notEquals(result.status, 200)) {
							layer.msg(result.message, { icon: 7 });
							return;
						}
						layer.msg(result.message, { icon: 1, time: 1000 });
						doSearch();
					}
				});
			},
			cancel: function(index) {
				layer.close(index);
			}
		});
}

self.doAddFunction = function(functionPId) {
	top.layer.open({
		type: 2,
		title: '新增功能',
		area: ['600px', '550px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/function/add.html?functionPId=" + functionPId + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>保存', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.doSubmitHandler(top, window);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}

self.doEditFunction = function(functionId) {
	//area: ['600px', ($(top.document.body).height() - 40) + 'px'],
	top.layer.open({
		type: 2,
		title: '编辑功能',
		area: ['600px', '550px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/function/edit.html?functionId=" + functionId + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>保存', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.doSubmitHandler(top, window);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}


self.doCollapse = function(node, childrens) {
	var flag = true;
	$.each(childrens, function(i, item) {
		if (item.type == 0) {
			flag = false;
			doCollapse(item, $('#data-table').treegrid("getChildren", item.functionId));
		}
	});
	if (node == null) {
		return;
	}
	if (flag) {
		$('#data-table').treegrid("collapse", node.functionId);
	}
}